package com.zhangyu.shadow.core.delegate.web;

import android.webkit.JavascriptInterface;

import com.alibaba.fastjson.JSON;
import com.zhangyu.shadow.core.delegate.web.event.Event;
import com.zhangyu.shadow.core.delegate.web.event.EventManager;

/**
 * @author zhangyu
 * @date 2017/11/9
 */

public class ShadowWebInterface {
    private final WebDelegate mWebDelegate;

    private ShadowWebInterface(WebDelegate webDelegate) {
        mWebDelegate = webDelegate;
    }

    static ShadowWebInterface create(WebDelegate webDelegate) {
        return new ShadowWebInterface(webDelegate);
    }

    @JavascriptInterface
    public String event(String params) {
        final String action = JSON.parseObject(params).getString("action");
        final Event event = EventManager.getInstance().createEvent(action);
        if(event != null){
            event.setAction(action);
            event.setContext(mWebDelegate.getContext());
            event.setDelegate(mWebDelegate);
            event.setUrl(mWebDelegate.getUrl());
            return event.execute(params);
        }
        return null;
    }
}
